﻿using UnityEngine;

public class BallMovement : MonoBehaviour 
{	
	private static readonly Vector2 destination = new Vector2(0.0f, 0.0f);
	
	private float speed = 40.0f;
	private float slowSpeed = 10.0f;
	
	private Vector2 direction = new Vector2(0.0f, 0.0f);
	
	private LineRenderer lineRenderer;
	
	private BallList ballList;	
	private BallColors ballColors;
	
	void Start() 
	{
		GameObject player = GameObject.FindGameObjectWithTag("Player");
		
		ballList = (BallList) player.GetComponent("BallList");
		ballColors = (BallColors) player.GetComponent("BallColors");
			
		direction.x = destination.x - transform.position.x;
		direction.y = destination.y + transform.position.y;
		direction.Normalize();
		
		lineRenderer = this.gameObject.AddComponent<LineRenderer>();
		lineRenderer.material = new Material(Shader.Find("Particles/Additive"));
		lineRenderer.SetWidth(9.0f, 9.0f);
		lineRenderer.SetVertexCount(2);
		lineRenderer.renderer.enabled = true;
	}
	
	void Update() 
	{		
		float speedThisStep = ballList.ballSpeedSlow ? slowSpeed : speed;
		
		Vector2 trans = direction * speedThisStep * Time.deltaTime;	
		
		transform.Translate(trans.x, 0.0f, trans.y);
		
		DrawHintLine();
	}
	
	void DrawHintLine() 
	{
		lineRenderer.SetPosition(0, transform.position);
		lineRenderer.SetPosition(1, destination);
				
		RaycastHit hit;		
		if (Physics.Raycast (transform.position, -transform.position, out hit)) 
		{
			if (hit.transform.gameObject.tag == "Slice") 
			{				
				Color lineColor = this.gameObject.renderer.material.color + hit.transform.gameObject.renderer.material.color;				
				lineRenderer.SetColors(this.gameObject.renderer.material.color, ballColors.NormalizeColor(lineColor));
			}
		}	
	}
}


